package org.gesplan.ui;

import ca.odell.glazedlists.swing.AutoCompleteSupport;
import java.awt.EventQueue;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.Query;
import javax.swing.JFrame;
import org.gesplan.controller.GenericController;
import org.gesplan.controller.WorkJpaController;
import org.gesplan.entity.Service;
import org.gesplan.entity.Staff;
import org.gesplan.entity.Task;
import org.gesplan.entity.Work;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.listeners.LoggingBindingListener;
import org.gesplan.listeners.SelectionListener;
import org.gesplan.util.RefreshWorker;
import org.gesplan.util.Utils;
import org.jdesktop.observablecollections.ObservableCollections;
import org.jdesktop.swingbinding.JTableBinding;


/**
 *
 * @author David
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class WorkPanel extends AbstractPanel {

    private JTableBinding jTableBinding;
    private final long MILIS_DIA = 24 * 60 * 60 * 1000;
    private boolean isLoaded = false;
    private static AutoCompleteSupport supportTask;
    private WorkAddFrame waf = null;
    

    public WorkPanel() {
        super();
        try {
            initComponents();
        } catch (Exception e) {
             logger.log(Level.SEVERE, bundle.getString("ERROR_DB_CONNECTION"), e);
        }
        if (!Beans.isDesignTime()) {
            initConfig();
        }

        this.addHierarchyListener(new HierarchyListener() {
            @Override
            public void hierarchyChanged(HierarchyEvent e) {
                if (HierarchyEvent.SHOWING_CHANGED == (e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED)) {
                    isLoaded = true;
                    changeFilter();
                }
            }
        });

    }


    private void initConfig() {

        super.abstractTable = masterTable;
        super.abstractQuery = tableQuery;
        super.abstractList = tableList;

        // Add Listeners
        LoggingBindingListener lbl = new LoggingBindingListener(saveButton);
        bindingGroup.addBindingListener(lbl);
        masterTable.getSelectionModel().addListSelectionListener(new SelectionListener(masterTable));

        // Autocomplete Support for combos
        GenericController.fillComboBox(bundle.getString("qryService"), filterServiceComboBox);
        GenericController.fillComboBox(bundle.getString("qryStaff"), filterStaffComboBox);
        supportTask = GenericController.fillComboBox(bundle.getString("qryTask"), filterTaskComboBox, supportTask);

        // Initialize filter dates
        dateEndDateChooser.setDate(new Date());
        long timeEnd = dateEndDateChooser.getDate().getTime();
        Integer days;
        try {
            days = Integer.parseInt(Utils.getConfigFile().getProperty("WORK_DAYS", "7"));
        } catch (NumberFormatException e) {
            days = 7;
        }
        Date dateStart = new Date(timeEnd - days * MILIS_DIA);
        dateStartDateChooser.setDate(dateStart);

        initSorter();
        setHeaders();
            
        masterTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    editRecord("edit");
                }
            }
        });

    }


    private void setHeaders(){
        
        Utils.setTableHeader(masterTable);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(30);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(70);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        masterTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(40);
        masterTable.getColumnModel().getColumn(5).setPreferredWidth(100);   
        masterTable.getColumnModel().getColumn(6).setPreferredWidth(100);  
        
    }
    
    
    private void changeService() {
        
        if (isLoaded) {
            Service service = null;
            try {
                service = (Service) filterServiceComboBox.getSelectedItem();
            } catch (ClassCastException ex) {
                logger.warning(ex.getMessage());
            }
            String jql = "SELECT t FROM Task t ";
            String where = null;
            if (service != null) {
                where = "WHERE ";
                where += "t.subgroupId.serviceId.id = '" + service.getId() + "'";
            }
            if (where != null) {
                jql += where;
            }
            jql += " ORDER BY t.description";
            supportTask = GenericController.fillComboBox(jql, filterTaskComboBox, supportTask);
        }
        
    }


    private void changeFilter() {

        if (isLoaded) {
            Service service = null;
            Staff staff = null;
            Task task = null;
            Date dateStart = null;
            Date dateEnd = null;
            // Get Filters
            try {
                dateStart = dateStartDateChooser.getDate();
                dateEnd = dateEndDateChooser.getDate();
                staff = (Staff) filterStaffComboBox.getSelectedItem();
                service = (Service) filterServiceComboBox.getSelectedItem();
                task = (Task) filterTaskComboBox.getSelectedItem();
            } catch (ClassCastException ex) {
                logger.warning(ex.getMessage());
            }

            // Build JQL Query
            String jql = "SELECT w FROM Work w ";
            String where = null;
            if (service != null) {
                where = "WHERE ";
                where += "w.taskId.subgroupId.serviceId.id = '" + service.getId() + "'";
            }
            if (staff != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "w.staffId.id = " + staff.getId();
            }
            if (task != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "w.taskId.id = '" + task.getId() + "'";
            }
            if (dateStart != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "w.dateWork >= '" + Utils.dateToString(dateStart) + "'";
            }
            if (dateEnd != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "w.dateWork <= '" + Utils.dateToString(dateEnd) + "'";
            }

            if (where != null) {
                jql += where;
            }
            jql += " ORDER BY w.id";
            updateTableBinding(jql);
        }

    }


    private void updateTableBinding(String jql) {
        
        if (!Beans.isDesignTime()) {
            tableQuery = entityManager.createQuery(jql);
            tableList = ObservableCollections.observableList(tableQuery.getResultList());
            jTableBinding.unbind();
            jTableBinding.setSourceObject(tableList);
            jTableBinding.bind();
            masterScrollPane.setViewportView(masterTable);
            setHeaders();
        }
        
    }


    private void resetFilters() {
        dateStartDateChooser.setDate(null);
        dateEndDateChooser.setDate(null);
        filterServiceComboBox.setSelectedIndex(-1);
        filterStaffComboBox.setSelectedIndex(-1);
        filterTaskComboBox.setSelectedIndex(-1);
    }


    @Override
    protected void refresh(Query queryParam, List<?> listObject) {
        refreshWorker = new RefreshWorker(this, entityManager, queryParam, listObject);
        refreshWorker.execute();
    }


    private void editRecord(String action) {
        MDIApplication mdi = MainClass.mdi;
        if (masterTable.getSelectedRow() != -1) {
            Work w = tableList.get(masterTable.convertRowIndexToModel(masterTable.getSelectedRow()));
            if (waf == null || !waf.isVisible()){
                waf = mdi.openWorkFrame(w, action, null);                
            } else{
                waf.setWork(w, action);
            }
        } else {
            waf = mdi.openWorkFrame(null, null);
        }
    }

    
    @Override
    protected void previous() {
        super.previous();
        editRecord("edit");        
    }
    
    
    @Override
    protected void next() {
        super.next();
        editRecord("edit");        
    }
    

    @Override
    protected void save() {
    	
        int selected = masterTable.getSelectedRow();
        if (selected > -1) {
            Work o = tableList.get(masterTable.convertRowIndexToModel(selected));
            WorkJpaController dao = new WorkJpaController();
            try {
                dao.edit(o);
                logger.info("Work.save: " + o.getId());
            } catch (NonexistentEntityException ex) {
                logger.severe(ex.getMessage());
            } catch (Exception ex) {
                logger.severe(ex.getMessage());
            }
        }
        
    }


    @Override
    protected void delete() {
    	
        if (deleteConfirm()) {
            List<Work> toRemove = new ArrayList<>(masterTable.getSelectedRows().length);
            WorkJpaController dao = new WorkJpaController();
            for (int idx = 0; idx < masterTable.getSelectedRows().length; idx++) {
                Work o = tableList.get(masterTable.convertRowIndexToModel(masterTable.getSelectedRows()[idx]));
                try {
                    toRemove.add(o);
                    dao.destroy(o.getId());
                    logger.info("Work.delete: " + o.getId());
                } catch (NonexistentEntityException ex) {
                    logger.log(Level.SEVERE, null, ex);
                }
            }
            tableList.removeAll(toRemove);
        }
        
    }

    
    // <editor-fold defaultstate="collapsed" desc="Auto Generated Code">      

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        tableQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryWork"));
        tableList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : tableQuery.getResultList();
        staffQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryStaff"));
        staffList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : staffQuery.getResultList();
        taskQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryTask"));
        taskList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : taskQuery.getResultList();
        serviceQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryService"));
        serviceList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : serviceQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        newButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        previousButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        filterStaffComboBox = new javax.swing.JComboBox();
        staffIdLabel1 = new javax.swing.JLabel();
        filterTaskComboBox = new javax.swing.JComboBox();
        taskIdLabel1 = new javax.swing.JLabel();
        dateStartDateChooser = new com.toedter.calendar.JDateChooser();
        staffIdLabel2 = new javax.swing.JLabel();
        staffIdLabel3 = new javax.swing.JLabel();
        dateEndDateChooser = new com.toedter.calendar.JDateChooser();
        filterServiceComboBox = new javax.swing.JComboBox();
        staffIdLabel4 = new javax.swing.JLabel();
        resetButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        setName("prova"); // NOI18N

        masterTable.setAutoCreateRowSorter(true);
        masterTable.setUpdateSelectionOnSort(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tableList, masterTable, "bindingTable");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${dateWork}"));
        columnBinding.setColumnName("Data");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${staffId}"));
        columnBinding.setColumnName("Treballador");
        columnBinding.setColumnClass(org.gesplan.entity.Staff.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${taskId}"));
        columnBinding.setColumnName("Tasca");
        columnBinding.setColumnClass(org.gesplan.entity.Task.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${timeElapsed}"));
        columnBinding.setColumnName("Hores");
        columnBinding.setColumnClass(Float.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${location}"));
        columnBinding.setColumnName("Ubicació");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${comments}"));
        columnBinding.setColumnName("Comentaris");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addPropertyChangeListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        if (masterTable.getColumnModel().getColumnCount() > 0) {
            masterTable.getColumnModel().getColumn(0).setPreferredWidth(15);
            masterTable.getColumnModel().getColumn(1).setResizable(false);
            masterTable.getColumnModel().getColumn(1).setPreferredWidth(40);
            masterTable.getColumnModel().getColumn(2).setResizable(false);
            masterTable.getColumnModel().getColumn(2).setPreferredWidth(100);
            masterTable.getColumnModel().getColumn(3).setResizable(false);
            masterTable.getColumnModel().getColumn(3).setPreferredWidth(100);
            masterTable.getColumnModel().getColumn(4).setMinWidth(30);
            masterTable.getColumnModel().getColumn(4).setPreferredWidth(30);
            masterTable.getColumnModel().getColumn(4).setMaxWidth(30);
        }
        this.jTableBinding = jTableBinding;

        newButton.setMnemonic('N');
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/gesplan/properties/Bundle"); // NOI18N
        newButton.setText(bundle.getString("NEW")); // NOI18N
        newButton.addActionListener(formListener);

        nextButton.setMnemonic('S');
        nextButton.setText(bundle.getString("NEXT")); // NOI18N
        nextButton.addActionListener(formListener);

        refreshButton.setMnemonic('T');
        refreshButton.setText(bundle.getString("REFRESH")); // NOI18N
        refreshButton.addActionListener(formListener);

        previousButton.setMnemonic('A');
        previousButton.setText(bundle.getString("PREVIOUS")); // NOI18N
        previousButton.addActionListener(formListener);

        deleteButton.setMnemonic('E');
        deleteButton.setText(bundle.getString("DELETE")); // NOI18N
        deleteButton.addActionListener(formListener);

        saveButton.setMnemonic('G');
        saveButton.setText(bundle.getString("SAVE")); // NOI18N
        saveButton.addActionListener(formListener);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, staffList, filterStaffComboBox, "bindFilterStaff");
        bindingGroup.addBinding(jComboBoxBinding);

        filterStaffComboBox.addActionListener(formListener);

        staffIdLabel1.setText("Treballador:");

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, taskList, filterTaskComboBox, "bindFilterTask");
        bindingGroup.addBinding(jComboBoxBinding);

        filterTaskComboBox.addActionListener(formListener);

        taskIdLabel1.setText("Tasca:");

        dateStartDateChooser.setToolTipText("dd-mm-yyyy"); // NOI18N
        dateStartDateChooser.setDateFormatString("dd-MM-yyyy");
        dateStartDateChooser.addPropertyChangeListener(formListener);

        staffIdLabel2.setLabelFor(dateStartDateChooser);
        staffIdLabel2.setText("Des de:");

        staffIdLabel3.setLabelFor(dateEndDateChooser);
        staffIdLabel3.setText("Fins:");

        dateEndDateChooser.setDateFormatString("dd-MM-yyyy");
        dateEndDateChooser.addPropertyChangeListener(formListener);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, serviceList, filterServiceComboBox, "bindFilterService");
        bindingGroup.addBinding(jComboBoxBinding);

        filterServiceComboBox.addActionListener(formListener);

        staffIdLabel4.setText("Servei:");

        resetButton.setMnemonic('R');
        resetButton.setText(bundle.getString("RESET")); // NOI18N
        resetButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(masterScrollPane)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(taskIdLabel1)
                                    .addComponent(staffIdLabel2)
                                    .addComponent(staffIdLabel1)
                                    .addComponent(staffIdLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(dateStartDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(staffIdLabel3)
                                        .addGap(18, 18, 18)
                                        .addComponent(dateEndDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(filterTaskComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 302, Short.MAX_VALUE)
                                        .addComponent(filterServiceComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(filterStaffComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(resetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(previousButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(nextButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(refreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 411, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dateStartDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dateEndDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(staffIdLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(staffIdLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filterStaffComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(staffIdLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(staffIdLabel4)
                    .addComponent(filterServiceComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(taskIdLabel1)
                    .addComponent(resetButton)
                    .addComponent(filterTaskComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(refreshButton)
                    .addComponent(deleteButton)
                    .addComponent(newButton)
                    .addComponent(previousButton)
                    .addComponent(nextButton))
                .addGap(18, 18, 18))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.beans.PropertyChangeListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == newButton) {
                WorkPanel.this.newButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nextButton) {
                WorkPanel.this.nextButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                WorkPanel.this.refreshButtonActionPerformed(evt);
            }
            else if (evt.getSource() == previousButton) {
                WorkPanel.this.previousButtonActionPerformed(evt);
            }
            else if (evt.getSource() == deleteButton) {
                WorkPanel.this.deleteButtonActionPerformed(evt);
            }
            else if (evt.getSource() == saveButton) {
                WorkPanel.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == filterStaffComboBox) {
                WorkPanel.this.filterStaffComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == filterTaskComboBox) {
                WorkPanel.this.filterTaskComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == filterServiceComboBox) {
                WorkPanel.this.filterServiceComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == resetButton) {
                WorkPanel.this.resetButtonActionPerformed(evt);
            }
        }

        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            if (evt.getSource() == masterTable) {
                WorkPanel.this.masterTablePropertyChange(evt);
            }
            else if (evt.getSource() == dateStartDateChooser) {
                WorkPanel.this.dateStartDateChooserPropertyChange(evt);
            }
            else if (evt.getSource() == dateEndDateChooser) {
                WorkPanel.this.dateEndDateChooserPropertyChange(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents


    public static void main(String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WorkPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WorkPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WorkPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WorkPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new WorkPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    // </editor-fold>          

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        editRecord("new");
    }//GEN-LAST:event_newButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        next();
    }//GEN-LAST:event_nextButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        refresh(tableQuery, tableList);
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
        previous();
    }//GEN-LAST:event_previousButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        delete();
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        save();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void filterStaffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterStaffComboBoxActionPerformed
        changeFilter();
    }//GEN-LAST:event_filterStaffComboBoxActionPerformed

    private void filterTaskComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterTaskComboBoxActionPerformed
        changeFilter();
    }//GEN-LAST:event_filterTaskComboBoxActionPerformed

    private void dateStartDateChooserPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateStartDateChooserPropertyChange
        changeFilter();
    }//GEN-LAST:event_dateStartDateChooserPropertyChange

    private void dateEndDateChooserPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateEndDateChooserPropertyChange
        changeFilter();
    }//GEN-LAST:event_dateEndDateChooserPropertyChange

    private void filterServiceComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterServiceComboBoxActionPerformed
        changeService();
        changeFilter();
    }//GEN-LAST:event_filterServiceComboBoxActionPerformed

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        resetFilters();
    }//GEN-LAST:event_resetButtonActionPerformed

    private void masterTablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_masterTablePropertyChange
        Utils.setRecordInfo(masterTable);
    }//GEN-LAST:event_masterTablePropertyChange
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser dateEndDateChooser;
    private com.toedter.calendar.JDateChooser dateStartDateChooser;
    private javax.swing.JButton deleteButton;
    private javax.swing.JComboBox filterServiceComboBox;
    private javax.swing.JComboBox filterStaffComboBox;
    private javax.swing.JComboBox filterTaskComboBox;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton previousButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton saveButton;
    private java.util.List<org.gesplan.entity.Service> serviceList;
    private javax.persistence.Query serviceQuery;
    private javax.swing.JLabel staffIdLabel1;
    private javax.swing.JLabel staffIdLabel2;
    private javax.swing.JLabel staffIdLabel3;
    private javax.swing.JLabel staffIdLabel4;
    private java.util.List<org.gesplan.entity.Staff> staffList;
    private javax.persistence.Query staffQuery;
    private java.util.List<org.gesplan.entity.Work> tableList;
    private javax.persistence.Query tableQuery;
    private javax.swing.JLabel taskIdLabel1;
    private java.util.List<org.gesplan.entity.Task> taskList;
    private javax.persistence.Query taskQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    
}